package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @Author : sunjun
 * @email : sunjun0207@163.com
 * @create 2019/11/14 21:31
 */
//会员登录
@RestController
@RequestMapping("/member")
public class MemberController {
    //注入memberService操作service
    @Reference
    public MemberService memberService;

    //注入jedis缓存
    @Autowired
    private JedisPool jedisPool;

    /*
    移动端-->手机端手机号和验证码快速登录
    HttpServletResponse:后台响应前台的数据
    1.根据手机号查询会员信息
    2.新增会员
     */
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map){
        //获取手机号和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //从Redis缓存中获取随机生成的验证码
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        //1.将两个验证码进行比对
        if(codeInRedis == null || !codeInRedis.equals(validateCode)){
            //验证码输入错误
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else{//验证码输入正确
            //2.判断当前用户是否为会员
            Member member = memberService.findByTelephone(telephone);
            if(member == null){//当前用户不是会员,
                //3.将当前用户自动注册为会员,
                //可以保存几个关键属性
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //4.登录成功,将telephone写回cookie,用于跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");//路径
            cookie.setMaxAge(60*60*24*30);//cookie有效期30天
            response.addCookie(cookie);
            //5.保存会员信息到Redis中
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);//30分钟
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        }
    }


}
